package com.kexilo.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.utils.ServletUtils;
import com.kexilo.core.common.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 * 
 * @author Kexilo
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    
    private static final Logger log = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException {
        int code = HttpStatus.UNAUTHORIZED.value();
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        
        log.warn("认证失败: {}", msg);
        ServletUtils.renderString(response, new ObjectMapper().writeValueAsString(R.fail(code, msg)));
    }
}
